<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>基于 Swoole 的聊天室</title>
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
  <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.min.js"></script>
  <script src="//res.layui.com/layui/release/layer/dist/layer.js?v=3111"></script>
  <!-- From http://www.cnblogs.com/felixnet/p/8019446.html -->
  <!-- From https://www.jianshu.com/p/f75abbc684d8 -->
  <style type="text/css">
  body{
    background-color: #fff;
    font-family: -apple-system;
    font-family: "-apple-system", "Helvetica Neue", "Roboto", "Segoe UI", sans-serif;
  }
  #main {
      width: 400px;
      margin:15px auto;
  }
  #msg {
    height:400px;
    overflow-y:auto;
    background-color: #ebebeb;
    border: 1px solid #eee;
    padding: 10px;
  }
  .chat-sender{
    clear:both;
    font-size: 80%;
  }
  .chat-sender div:nth-of-type(1){
    float: left;
  }
  .chat-sender div:nth-of-type(2){
    margin: 0 50px 2px 50px;
    padding: 0px;
    color: #848484;
    font-size: 70%;
    text-align: left;
  }
  .chat-sender div:nth-of-type(3){
    background-color: white;
    /*float: left;*/
    margin: 0 50px 10px 50px;
    padding: 10px 10px 10px 10px;
    border-radius:7px;
    text-indent: -12px;
  }

  .chat-receiver{
    clear:both;
    font-size: 80%;
  }
  .chat-receiver div:nth-of-type(1){
    float: right;
  }
  .chat-receiver div:nth-of-type(2){
    margin: 0px 50px 2px 50px;
    padding: 0px;
    color: #848484;
    font-size: 70%;
    text-align: right;
  }
  .chat-receiver div:nth-of-type(3){
    background-color: #b2e281;
    margin: 0px 50px 10px 50px;
    padding: 10px 10px 10px 10px;
    border-radius:7px;
  }

  .chat-receiver div:first-child img,
  .chat-sender div:first-child img{
    width: 40px;
    height: 40px;
  }

  .chat-left_triangle{
    height: 0px;
    width: 0px;
    border-width: 6px;
    border-style: solid;
    border-color: transparent white transparent transparent;
    position: relative;
    left: -22px;
    top: 3px;
  }
  .chat-right_triangle{
    height: 0px;
    width: 0px;
    border-width: 6px;
    border-style: solid;
    border-color: transparent transparent transparent #b2e281;
    position: relative;
    right:-22px;
    top:3px;
  }

  .chat-notice{
    clear: both;
    font-size: 70%;
    color: white;
    text-align: center;
    margin-top: 15px;
    margin-bottom: 15px;
  }
  .chat-notice span{
    background-color: #cecece;
    line-height: 25px;
    border-radius: 5px;
    padding: 5px 10px;
  }
  </style>
</head>
<body>

<div id="main">

        <div id="msg">
</div>

    <div class="action" style="margin-top: 15px">
        <textarea style="width: 100%;height:80px;" type="text" id="text"></textarea>
        <div style="margin-top:10px;">
            <button type="button" style="" onclick="send()">发送</button>
            <button type="button"  style="margin-left: 10px;" onclick="closeChat()">断开</button>
        </div>
    </div>
</div>

{tagself}
<script type="text/javascript">
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

var msg = document.getElementById("msg");
var wsServer = 'ws://0.0.0.0:9502/websocket/test';
//调用websocket对象建立连接：
//参数：ws/wss(加密)：//ip:port （字符串）
var websocket = new WebSocket(wsServer);

// onopen 监听连接打开
websocket.onopen = function (evt) {
    //msg.innerHTML = websocket.readyState;
    msg.innerHTML = '<div class="chat-notice">'+
    '<span>欢迎光临聊天室</span>'+
    '</div>';
};

function send(){
    if (3 === websocket.readyState) {
        layer.msg('聊天室已经断开,请刷新重现连接');
        return;
    }

    var text = document.getElementById('text').value;

    if (!text) {
        layer.msg('请输入聊天消息');
        return;
    }

    document.getElementById('text').value = '';
    var date = new Date().Format("MM-dd hh:mm:ss");

    msg.innerHTML += '<div class="chat-notice">'+
        '<span>'+date+'</span>'+
        '</div>';

    msg.innerHTML += '<div class="chat-receiver">'+
        '<div><img src=""></div>'+
        '<div>我</div>'+
        '<div>'+
        '<div class="chat-right_triangle"></div>'+
        '<span>'+ text+'</span>'+
        '</div>'+
        '</div>';

    //向服务器发送数据
    websocket.send(text);

    scroll();
}

function isJSON(str) {
    if (typeof str == 'string') {
        try {
            JSON.parse(str);
            return true;
        } catch(e) {
            return false;
        }
    }
}

function closeChat()
{
    if (3 === websocket.readyState) {
        layer.msg('聊天室已经断开,请刷新重现连接');
        return;
    }

    websocket.close();
    layer.msg('聊天室已经断开');
}

function scroll()
{
    $("#msg").animate({"scrollTop":$("#msg")[0].scrollHeight},400);
}

//监听连接关闭
websocket.onclose = function (evt) {
    console.log("Disconnected");
};

//onmessage 监听服务器数据推送
websocket.onmessage = function (evt) {
    if (3 === websocket.readyState) {
        layer.msg('聊天室已经断开,请刷新重现连接');
        return;
    }
    
    layer.msg('您有新消息啦！');
    var date = new Date().Format("MM-dd hh:mm:ss");

    if (isJSON(evt.data)) {
        var result = JSON.parse(evt.data);

        msg.innerHTML += '<div class="chat-notice">'+
            '<span>'+date+'</span>'+
            '</div>';

        msg.innerHTML += '<div class="chat-sender">'+
            '<div><img src=""></div>'+
            '<div>'+result.fd+'</div>'+
            '<div>'+
            '<div class="chat-left_triangle"></div>'+
            '<span>'+result.data+'</span>'+
            '</div>'+
        '</div>';
    } else {
        msg.innerHTML += '<div class="chat-notice">'+
            '<span>'+evt.data+'</span>'+
            '</div>'; 
    }

    scroll();
};

//监听连接错误信息
websocket.onerror = function (evt, e) {
    console.log('Error occured: ' + evt.data);
};

$(window).unload(function(){ 
    closeChat();
}); 
</script>
{/tagself}
</body>
</html>